package com.winning.pmph.service;

import com.winning.pmph.entity.IncreaseBook;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.winning.pmph.entity.IncreaseQrCode;
import com.winning.pmph.mapper.IncreaseQrCodeMapper;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lbm
 * @since 2021-12-30
 */
@Service
public class IncreaseQrCodeService extends ServiceImpl<IncreaseQrCodeMapper, IncreaseQrCode>{

    @Resource
    IncreaseBookService increaseBookService;

    /**
     * 素材码列表
     * @param bookId
     * @param qrName
     * @param resourceType
     * @param start
     * @param size
     * @return
     */
    public List<Map<String, Object>> list(String bookId, String qrName, String resourceType, int start, int size) {
        if(start < 1) {
            return this.baseMapper.list(bookId, qrName, resourceType, -1, -1);
        }else {
            return this.baseMapper.list(bookId, qrName, resourceType, (start - 1) * size, size);
        }
    }

    public int listCount(String bookId, String qrName, String resourceType) {
        return this.baseMapper.listCount(bookId, qrName, resourceType);
    }

    /**
     * 章节码树
     * @param bookId
     * @return
     */
    public List<Map<String, Object>> treeChapterQr(String bookId) {
        List<Map<String, Object>> list = new ArrayList<>();
        List<Map<String, Object>> datas = this.baseMapper.listChapterQr(bookId);
        int maxLevel = getMaxCateLevel(datas,bookId);

        IncreaseBook increaseBook = increaseBookService.getById(bookId);
        String bookName = increaseBook.getBookName();
        Map<String, Object> root = new HashMap<>();
        root.put("id", bookId);
        root.put("pid", "0");
        root.put("name", bookName);
        root.put("label", bookName);
        root.put("cate_level", maxLevel);
        root.put("res_count", 0);
        IncreaseQrCode bookQr = this.lambdaQuery().eq(IncreaseQrCode::getSourceId, bookId).eq(IncreaseQrCode::getSourceType, 1).one();
        if(bookQr != null) {
            root.put("code", bookQr.getCode());
            root.put("qr_create_time", bookQr.getCreateTime());
            root.put("scan_count_before", bookQr.getScanCountBefore());
            root.put("scan_count_after", bookQr.getScanCountAfter());
            root.put("scan_qulity_before",bookQr.getScanQulityBefore());
            root.put("qr_name", bookQr.getName());
            root.put("qr_id", bookQr.getId());
        }
        cateTree(datas, root);
        list.add(root);
        return list;
    }
    
    private int getMaxCateLevel(List<Map<String, Object>> datas,String pid) {
    	int level = 0;
    	boolean flag = true;
        int i = 0;
        List<Map<String, Object>> tempList = new ArrayList<>();
        Map<String, Object> temp = new HashMap<>();
        temp.put("id", pid);
        tempList.add(temp);
        while(flag) {
        	List<Map<String, Object>> tempList1 = new ArrayList<>();
        	for (Map<String, Object> data : datas) {
        		String tempPid = (String) data.get("pid");
        		for(Map<String, Object> tempData : tempList) {
        			String id = (String) tempData.get("id");
                	if(id.equals(tempPid)) {
                		data.put("cate_level", level+1);
                		tempList1.add(data);
                	}
        		}
			}
        	if(tempList1.size()>0) {
        		level++;
        		tempList = tempList1;
        	} else {
        		flag = false;
        	}
        	if(i>1000) {
        		flag = false;
        	}
        	i++;//用于防止陷入无限循环的变量
        }
        return level;
    }

    private static void cateTree(List<Map<String, Object>> listCate, Map<String, Object> parent) {
        String id = parent.get("id").toString();
        List<Map<String, Object>> childrenList = listCate.stream().filter(item -> {
            String pid = item.get("pid").toString();
            return id.equals(pid);
        }).peek(item -> item.put("label", item.get("name").toString())).collect(Collectors.toList());
        parent.put("children", childrenList);

        for (Map<String, Object> child : childrenList) {
            cateTree(listCate, child);
        }
        StringBuilder childIds = new StringBuilder();
        for (Map<String, Object> child : childrenList) {
            parent.put("res_count", Integer.parseInt(parent.get("res_count").toString()) + Integer.parseInt(child.get("res_count").toString()));
            String resPath = "";
            if(parent.get("res_path") != null && StringUtils.isNotBlank(parent.get("res_path").toString())) {
                resPath = parent.get("res_path").toString();
            }
            if(child.get("res_path") != null && StringUtils.isNotBlank(child.get("res_path").toString())) {
                if(StringUtils.isNotBlank(resPath)) {
                    resPath += "~";
                }
                resPath += child.get("res_path").toString();
            }
            parent.put("res_path", resPath);
            childIds.append(child.get("childIds").toString()).append(",");
        }
        childIds.append(id);
        parent.put("childIds", childIds.toString());
    }

    /**
     * 章节码列表
     * @param bookId
     * @return
     */
    public List<Map<String, Object>> listChapterQr(String bookId) {
        List<Map<String, Object>> datas = this.baseMapper.listChapterQr(bookId);
        int maxLevel = 0;
        for(Map<String, Object> data : datas) {
            if(data.get("cate_level") != null) {
                maxLevel = Math.max(Integer.parseInt(data.get("cate_level").toString()), maxLevel);
            }
        }
        IncreaseBook increaseBook = increaseBookService.getById(bookId);
        String bookName = increaseBook.getBookName();
        Map<String, Object> root = new HashMap<>();
        root.put("id", bookId);
        root.put("pid", "0");
        root.put("name", bookName);
        root.put("label", bookName);
        root.put("cate_level", maxLevel);
        root.put("res_count", 0);
        IncreaseQrCode bookQr = this.lambdaQuery().eq(IncreaseQrCode::getSourceId, bookId).eq(IncreaseQrCode::getSourceType, 1).one();
        if(bookQr != null) {
            root.put("code", bookQr.getCode());
            root.put("qr_create_time", bookQr.getCreateTime());
            root.put("scan_count_before", bookQr.getScanCountBefore());
            root.put("scan_count_after", bookQr.getScanCountAfter());
            root.put("scan_qulity_before",bookQr.getScanQulityBefore());
            root.put("qr_name", bookQr.getName());
        }
        datas.add(root);
        return datas;
    }
}
